import os
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from ui.UIFunction import readFile, createWordDict, createImg
from ui.UIFunctions import *
from ui.mainWindow import Ui_MainWindow
from toast.toast import DialogOver


class MainWindow(QMainWindow, Ui_MainWindow):


    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # basic interface
        self.setupUi(self)
        self.setAttribute(Qt.WA_TranslucentBackground)  # rounded transparent
        self.setWindowFlags(Qt.FramelessWindowHint)  # Set window flag: hide window borders

        # 添加UI功能
        UIFuncitons.uiDefinitions(self)

        # 右上角按钮——窗口事件
        self.btn_max.clicked.connect(lambda: self.showNormal() if self.isMaximized() else self.showMaximized())
        self.btn_min.clicked.connect(lambda: self.showMinimized())
        self.btn_stop.clicked.connect(lambda: sys.exit())
        #------------------------------------------------------------------------------------------
        # ------------------------------------------------------------------------------------------
        # 基本数据
        self.page = 0  # 选项卡页面
        self.word_frequencies = None  # 词语字典
        self.word_color = None   # 颜色字典
        self.img_path = None  # 图片路径
        self.font_path = None # 字体路径
        self.txt = None # 词语
        self.composite_img = None # 图片

        self.is_use_color = False
        self.is_use_bgcolor = False
        self.is_use_reapt = False
        self.is_use_outline_color = False
        self.is_use_outline_width = False


        # 绑定页面切换事件
        self.tabWidget.currentChanged.connect(lambda index: setattr(self, 'page', index))

        # 绑定中部按钮事件
        self.import_button.clicked.connect(self.import_content)    # 导入
        self.submit_button.clicked.connect(self.createWordCloud)        # 生成图片
        self.save_button.clicked.connect(self.save_img)           # 保存图片

        # 加入一行 & 减去一行
        self.add_button.clicked.connect(lambda: self.tableWidget.insertRow(self.tableWidget.rowCount()))
        self.sub_button.clicked.connect(lambda: self.tableWidget.removeRow(self.tableWidget.rowCount() - 1))




        # 设置check
        self.use_color_button.setChecked(self.is_use_color)
        self.use_bgcolor_button.setChecked(self.is_use_bgcolor)
        self.use_reapt_button.setChecked(self.is_use_reapt)

        self.use_outline_color_button.setChecked(self.is_use_outline_color)
        self.use_outline_width_button.setChecked(self.is_use_outline_width)

        self.use_color_button.toggled.connect(self.check_use_color)  # 是否用系统色卡
        self.use_bgcolor_button.toggled.connect(self.check_use_bgcolor)  # 是否用 背景颜色
        self.use_reapt_button.toggled.connect(self.check_use_reapt)  # 是否用重复词语

        self.use_outline_color_button.toggled.connect(self.check_use_outline_color)  # 是否用 轮廓颜色
        self.use_outline_width_button.toggled.connect(self.check_use_outline_width)  # 是否用 轮廓厚度
        # 添加选项
        # colormap 配色集
        for i in ['Sequential', 'Sequential2', 'Diverging', 'Cyclic', 'Qualitative', 'Miscellaneous']:
            self.color_class_box.addItem(i)
        self.color_class_box.currentIndexChanged.connect(self.onColorClassChanged) # 连接选项卡信号

        # 观看视频
        self.video_button.clicked.connect(lambda: QDesktopServices.openUrl(QUrl("https://space.bilibili.com/279540198")))

        # 创建颜色字典
        self.color_dict = {
            'Sequential': ['viridis', 'plasma', 'inferno', 'magma', 'cividis', 'Greys', 'Purples', 'Blues', 'Greens','Oranges', 'Reds','YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu','GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn'],
            'Sequential2': ['binary', 'gist_yarg', 'gist_gray', 'gray', 'bone','pink', 'spring', 'summer', 'autumn', 'winter', 'cool','Wistia', 'hot', 'afmhot', 'gist_heat', 'copper'],
            'Diverging': ['PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu', 'RdYlBu','RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'],
            'Cyclic': ['twilight', 'twilight_shifted', 'hsv'],
            'Qualitative': ['Pastel1', 'Pastel2', 'Paired', 'Accent', 'Dark2','Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c'],
            'Miscellaneous': ['flag', 'prism', 'ocean', 'gist_earth', 'terrain','gist_stern', 'gnuplot', 'gnuplot2', 'CMRmap','cubehelix', 'brg', 'gist_rainbow', 'rainbow', 'jet','turbo', 'nipy_spectral', 'gist_ncar']
        }

    # 选项卡切换
    def onColorClassChanged(self):
        self.color_style_box.clear()
        for color in self.color_dict.get(self.color_class_box.currentText(), []):
            self.color_style_box.addItem(color)

    #
    # Get the mouse position (used to hold down the title bar and drag the window)
    def mousePressEvent(self, event):
        p = event.globalPosition()
        globalPos = p.toPoint()
        self.dragPos = globalPos

    # Optimize the adjustment when dragging the bottom and right edges of the window size
    def resizeEvent(self, event):
        # Update Size Grips
        UIFuncitons.resize_grips(self)

    # 是否用系统色卡
    def check_use_color(self):
        if self.use_color_button.checkState() == Qt.CheckState.Unchecked:
            self.is_use_color = False
        elif self.use_color_button.checkState() == Qt.CheckState.Checked:
            self.is_use_color = True
        DialogOver(parent=self, text=f" 是否使用系统色卡:{self.is_use_color}", title="设置修改", flags="warning")

    # 是否用 背景颜色
    def check_use_bgcolor(self):
        if self.use_bgcolor_button.checkState() == Qt.CheckState.Unchecked:
            self.is_use_bgcolor = False
            self.bg_color_input.setEnabled(False)
        elif self.use_bgcolor_button.checkState() == Qt.CheckState.Checked:
            self.is_use_bgcolor = True
            self.bg_color_input.setEnabled(True)
        DialogOver(parent=self, text=f"是否自定义背景颜色:{self.is_use_bgcolor}", title="设置修改", flags="warning")


    # 是否 重复
    def check_use_reapt(self):
        if self.use_reapt_button.checkState() == Qt.CheckState.Unchecked:
            self.is_use_reapt = False
        elif self.use_reapt_button.checkState() == Qt.CheckState.Checked:
            self.is_use_reapt = True

    # 是否 自定义轮廓颜色
    def check_use_outline_color(self):
        if self.use_outline_color_button.checkState() == Qt.CheckState.Unchecked:
            self.is_use_outline_color = False
            self.outline_color_input.setEnabled(False)
        elif self.use_outline_color_button.checkState() == Qt.CheckState.Checked:
            self.is_use_outline_color = True
            self.outline_color_input.setEnabled(True)
        DialogOver(parent=self, text=f"是否自定义轮廓颜色:{self.is_use_outline_color}", title="设置修改", flags="warning")

    # 是否自定义 轮廓厚度
    def check_use_outline_width(self):
        if self.use_outline_width_button.checkState() == Qt.CheckState.Unchecked:
            self.is_use_outline_width = False
            self.outline_width_input.setEnabled(False)
        elif self.use_outline_width_button.checkState() == Qt.CheckState.Checked:
            self.is_use_outline_width = True
            self.outline_width_input.setEnabled(True)
        DialogOver(parent=self, text=f"是否自定义轮廓宽度:{self.is_use_outline_width}", title="设置修改", flags="warning")


    # 导入文件
    def import_content(self):
        if self.page == 3:
            DialogOver(parent=self, text='当前页面无需导入', title="错误", flags="danger")
            return

        file_dialog = QFileDialog(self)
        name_filters = {
            0: "Table Files (*.csv *.xlsx)",
            1: "Image Files (*.png)",
            2: "Font Files (*.ttf)"
        }
        name_filter = name_filters.get(self.page, "All Files (*)")
        file_path, _ = file_dialog.getOpenFileName(self, "选择文件", "", name_filter)

        # 读取内容
        if file_path:
            with open(file_path, 'r') as file:
                try:
                    file_name = readFile(self, self.page, file_path)
                    DialogOver(parent=self, text=f"已导入:{file_name}", title="运行成功", flags="success")
                except Exception as e:
                    DialogOver(parent=self, text=str(e), title="运行失败", flags="danger")

    # 生成词云图片
    def createWordCloud(self):
        if createWordDict(self) is None:
            return
        # 判断 生成图片的相关信息
        if self.img_path is None or self.font_path is None:
            DialogOver(parent=self, text='还未导入字体或图片哟！', title="运行失败", flags="danger")
            return

        #————————————————————————————————————————————————————————————————————————————————————————
        # 生成图片
        #————————————————————————————————————————————————————————————————————————————————————————
        createImg(self)

    # 保存结果到文件
    def save_img(self):
        if self.composite_img is None:
            DialogOver(parent=self, text='生成图片后，才可以保存', title="保存失败", flags="danger")
            return

        # 定义基础文件名
        counter = 1
        # print(os.getcwd())
        path = os.getcwd()+'\\res\\'
        filename = os.getcwd()+'\\res\\' + 'result_'+ str(counter) + '.png'

        # 创建文件夹
        if not os.path.exists(path):
            os.makedirs(path)


        # 检查文件是否存在，如果存在则增加后缀数字直到找到未使用的文件名
        while os.path.exists(filename):
            filename = os.getcwd()+'\\res\\' + 'result_'+ str(counter) + '.png'
            counter += 1

        # 保存图片  路径： E:\A-word-cloud\res\result_1.png
        DialogOver(parent=self, text=f"已保存:{filename}", title="运行成功", flags="success")
        self.composite_img.save(filename,format='PNG')
    # Get the mouse position (used to hold down the title bar and drag the window)
    def mousePressEvent(self, event):
        p = event.globalPosition()
        globalPos = p.toPoint()
        self.dragPos = globalPos

    # Optimize the adjustment when dragging the bottom and right edges of the window size
    def resizeEvent(self, event):
        # Update Size Grips
        UIFuncitons.resize_grips(self)

    # Exit Exit thread, save settings
    def closeEvent(self, event):
        sys.exit(0)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    Home = MainWindow()
    Home.show()
    sys.exit(app.exec())  
